package study.thread.ReturnMessages;
import java.io.*;
import java.security.*;

/**
 * @author Java Networking Programming, 3rd , Ch5
 * Using thread and this thread can return message
 * Main program in ReturnDigestUserInterface class
 *
 */
public class ReturnDigest extends Thread {

  private File input;
  private byte[] digest;

  public ReturnDigest(File input) {
   this.input = input;
  }

  public void run() {
    try {
      FileInputStream in = new FileInputStream(input);
      MessageDigest sha = MessageDigest.getInstance("SHA");
      DigestInputStream din = new DigestInputStream(in, sha);
      int b;
      while ((b = din.read()) != -1) ;
      din.close();
      digest = sha.digest();
    }
    catch (IOException ex) {
      System.err.println(ex);
    }
    catch (NoSuchAlgorithmException ex) {
      System.err.println(ex);
    }
    
  }
  
  /**
 *getDigest 
 *
 *@return Message Digest in byte array
 */
public byte[] getDigest() {
    return digest;
  }

public static void main(String[] args) {
	  
    for (int i = 0; i < args.length; i++) {
    
      // Calculate the digest
      File f = new File(args[i]);
      ReturnDigest dr = new ReturnDigest(f);
      dr.start();
      
      // Now print the result
      StringBuffer result = new StringBuffer(f.toString());
      result.append(": ");
      byte[] digest = dr.getDigest();						//	program goto here is faster than its calculates the message digest		
      for (int j = 0; j < digest.length; j++) {				// so digest may be null. 
        result.append(digest[j] + " ");
      }  
      System.out.println(result);
      
    }
  
  }


}
